# -*- coding: utf-8 -*-
"""
发布已存在的Agent
"""

import os
import sys
import json
from pathlib import Path
from dotenv import load_dotenv

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

# 加载环境变量
load_dotenv(project_root / '.env')

from scripts.auto_publish_agent import AgentAutoPublisher


def main():
    """发布已存在的Agent"""

    # 已存在的AppID
    app_id = "d3rincoiqq79p3439na0"

    print("=" * 80)
    print(f"发布已存在的Agent: {app_id}")
    print("=" * 80)

    # 创建发布器
    publisher = AgentAutoPublisher()

    # 直接设置app_id（跳过创建Agent步骤）
    publisher.app_id = app_id

    try:
        # 步骤1: 创建API密钥
        print("\n[步骤1] 创建API密钥...")
        publisher.create_api_key(name="自动发布API密钥")
        print(f"[成功] APIKeyID: {publisher.api_key_id}")
        print(f"[成功] APIKey: {publisher.api_key[:30]}...")

        # 步骤2: 发布到智能体中心
        print("\n[步骤2] 发布到智能体中心...")
        publisher.publish_to_center(
            version="1.0.0",
            version_desc="通过自动化脚本发布",
            category_codes=["WorkAssistant"],  # 工作助手分类
            auth_type="Public",
            auth_range_type="All"
        )
        print(f"[成功] PublishID: {publisher.publish_id}")

        # 步骤3: 自动审核
        print("\n[步骤3] 自动通过审核...")
        approval_success = False
        try:
            # 稍等一下让审批单创建完成
            import time
            time.sleep(2)

            # 自动通过审批
            publisher.auto_approve()
            approval_success = True
            print("[成功] 审核已自动通过")
        except Exception as e:
            print(f"[警告] 自动审核失败: {str(e)}")
            print("       可能需要手动在平台上审核")

        # 步骤4: 开启API访问
        print("\n[步骤4] 开启API访问...")
        try:
            publisher.enable_api_access(enable=True)
            api_enabled = True
        except Exception as api_error:
            print(f"[警告] 开启API访问失败: {str(api_error)}")
            print("       您可能需要手动在平台上开启API访问")
            api_enabled = False

        # 步骤5: 获取已发布的App信息
        print("\n[步骤5] 获取已发布的App信息...")
        app_info_result = publisher.get_published_app_info()
        app_info = app_info_result.get("Response", {})

        # 显示结果
        print("\n" + "=" * 80)
        print("发布完成！请保存以下重要信息：")
        print("=" * 80)
        print(f"\nAppID: {publisher.app_id}")
        print(f"API Key: {publisher.api_key}")
        print(f"API Key ID: {publisher.api_key_id}")
        print(f"Publish ID: {publisher.publish_id}")
        print(f"\n应用名称: {app_info.get('AppName', 'N/A')}")
        print(f"是否已发布: {app_info.get('IsPublished', False)}")
        print(f"已发布渠道: {app_info.get('PublishedChannels', [])}")
        print(f"审核状态: {'通过' if approval_success else '待审核或失败'}")
        print(f"API访问状态: {'已开启' if api_enabled else '未开启'}")

        # 保存结果到文件
        result = {
            "app_id": publisher.app_id,
            "api_key": publisher.api_key,
            "api_key_id": publisher.api_key_id,
            "publish_id": publisher.publish_id,
            "approval_success": approval_success,
            "api_enabled": api_enabled,
            "app_info": app_info
        }

        output_file = project_root / "scripts" / "existing_agent_result.json"
        with open(output_file, "w", encoding="utf-8") as f:
            json.dump(result, f, ensure_ascii=False, indent=2)

        print(f"\n[信息] 完整结果已保存到: {output_file}")

        print("\n" + "=" * 80)
        print("使用指南：")
        print("=" * 80)
        print(f"1. 使用以下信息调用API：")
        print(f"   - AppID: {publisher.app_id}")
        print(f"   - API Key: {publisher.api_key}")
        print(f"\n2. API调用示例：")
        print(f"   curl -X POST https://api.example.com/v1/chat \\")
        print(f"     -H 'Authorization: Bearer {publisher.api_key}' \\")
        print(f"     -H 'Content-Type: application/json' \\")
        print(f"     -d '{{\"app_id\": \"{publisher.app_id}\", \"message\": \"Hello\"}}'")
        print("=" * 80)

        return result

    except Exception as e:
        print(f"\n[错误] 发布失败: {str(e)}")
        import traceback
        traceback.print_exc()
        sys.exit(1)


if __name__ == "__main__":
    main()
